package com.qk.management.service.serviceimpl;

import cn.hutool.core.util.ObjectUtil;
import com.qk.domain.UserLoginDO;
import com.qk.entity.User;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.LoginException;
import com.qk.management.mapper.LoginMapper;
import com.qk.management.service.LoginService;
import com.qk.common.util.jwt.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

/**
 * @author 上官徵羽
 * @version 1.0
 * @since 2025-10-09 21:41
 */
@Service
@SuppressWarnings("all")
public class LoginServiceImpl implements LoginService {
    private static final Integer STATUS_STOP = 0;
    @Autowired
    private LoginMapper loginMapper;
    @Override
    public UserLoginDO loginVerification(String username, String password) {
        if (ObjectUtils.isEmpty(username) || ObjectUtils.isEmpty(password)) {
            LoginException.throwLoginException(ParamEnum.THE_USERNAME_OR_PASSWORD_CANNOT_BE_EMPTY);
        }
        String md5Password = DigestUtils.md5DigestAsHex((password + "123").getBytes());
        User user = loginMapper.loginVerification(username, md5Password);
        if (ObjectUtils.isEmpty(user)) {
            LoginException.throwLoginException(ParamEnum.WRONG_ACCOUNT_OR_PASSWORD);
        }
        if(ObjectUtil.equals(STATUS_STOP, user.getStatus())){
            LoginException.throwLoginException(ParamEnum.USER_IS_STOP);
        }
        return UserLoginDO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .name(user.getName())
                .image(user.getImage())
                .roleLabel(loginMapper.getLabelByRoleId(user.getRoleId()))
                .token(JwtUtils.builderJwts(user))
                .build();
    }
}
